package cn.whpu.jdbctemplate;

import cn.whpu.domain.Account;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * jdbcTemplate的基本使用CRUD
 */
public class JdbcTemplateDemo3 {
    public static void main(String[] args) {
        //获取容器
        ApplicationContext ac= new ClassPathXmlApplicationContext("bean.xml");
        JdbcTemplate jt = ac.getBean("jdbcTemplate",JdbcTemplate.class);
        //jt.execute("insert into account(name,money) values('ddd',1000)");
        //查询所有
//        List<Account> accounts = jt.query("select * from account where money>?", new AccountRowMapper(),1000);
        /*List<Account> accounts = jt.query("select * from account where money>?", new BeanPropertyRowMapper<Account>(Account.class),1000);
        for (Account account :accounts
                ) {
            System.out.println(account);
        }*/
        //查询返回一列一行
        Long count = jt.queryForObject("select count(*) from account where money>?", Long.class, 900f);
        System.out.println(count);
    }
}

/**
 * 定义Account的封装策略
 */
class AccountRowMapper implements RowMapper{
    /**
     *
     * @param resultSet
     * @param i
     * @return
     * @throws SQLException
     */
    public Account mapRow(ResultSet resultSet, int i) throws SQLException {
        Account account =new Account();
        account.setId(resultSet.getInt("id"));
        account.setName(resultSet.getString("name"));
        account.setMoney(resultSet.getFloat("money"));
        return account;
    }
}
